/**
 * zmn渠道管理-订单配置
 * 文件命名格式：zmn.模块.表/功能.js
 * @author xiangjunming
 * @since 2019/08/22 18:06
 */
layui.define(['form', 'layedit', 'zmnSelect', 'zmnOmsSelect', 'xmSelect'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    let zmnOmsSelect = layui.zmnOmsSelect;
    let zmnSelect = layui.zmnSelect;
    var xmSelect = layui.xmSelect;

    let initCollectionLimit = [{
        name: '下单预付全款',
        value: 1
    }, {
        name: '工程师收全款',
        value: 2
    }, {
        name: '预付+尾款',
        value: 3
    }, {
        name: '后付费',
        value: 4
    }]

    let formParams = {
        // C端收款限制
        c_side_collection_limit: initCollectionLimit,
        // F端收款限制
        f_side_collection_limit: initCollectionLimit,
        // 工单取消控制
        work_order_cancellation_control: [{
            name: '运营后台',
            value: 1
        }, {
            name: '工程师APP',
            value: 2
        }, {
            name: '服务商门户',
            value: 3
        }, {
            name: '第三方APP',
            value: 4
        }],
        // 服务审核
        service_audit: [{
            name: '不需审核',
            value: 1
        }, {
            name: 'F端需审核',
            value: 2
        }, {
            name: '保外审核',
            value: 3
        }, {
            name: '均需审核',
            value: 4
        }]
    }

    form.verify({
        positive: function (value) {
            if (value) {
                if (!/^[1-9][0-9]*$/.test(value)) {
                    return "请输入大于0的正整数";
                }
            }
        }
    });

    form.render(null, "zmn-form");
    let priceAuditDeptId = json.priceAuditDeptId;

    $("#zmn-form-reset").click(function () {
        if (json.orderConfig.inviteComment == 1) {
            $("#inviteCommentPlatDiv").hide();
            $("#inviteCommentExplainDiv").hide();
        } else {
            $("#inviteCommentPlatDiv").show();
            $("#inviteCommentExplainDiv").show();
        }

        if (json.orderConfig.guideThirdPartPay == 1) {
            $("#payPlatDiv").hide();
            $("#payExplainDiv").hide();
            $("#showPayQrDiv").hide();
        } else {
            $("#payPlatDiv").show();
            $("#payExplainDiv").show();
            $("#showPayQrDiv").show();
        }
    });

    // 提交
    form.on('submit(zmn-form-submit)', function (obj) {
        let data = obj.field;
        let flag = verifySubmitData(data);
        if (!flag) {
            return false;
        }

        data.priceAuditDeptId = priceAuditDeptId;
        if (data.auditType == 1) {
            data.priceAuditDeptId = null;
            data.auditMinPrice = null;
        } else {
            if (zmnUtil.isEmptyNull(priceAuditDeptId) || priceAuditDeptId <= 0) {
                layer.msg("审核部门不能为空", {"icon": 2});
                return false;
            }
            if (zmnUtil.isEmptyNull(data.auditMinPrice)) {
                layer.msg("审核起始金额不能为空", {"icon": 2});
                return false;
            }

            data.auditMinPrice = data.auditMinPrice * 100;
        }

        // let completeNodesArr = new Array();
        // let completeNode = $('input[name="workOrderCompleteType"]');
        // for(let k in completeNode){
        //     if(completeNode[k].checked)
        //         completeNodesArr.push(completeNode[k].value);
        // }
        // if(completeNodesArr.length == 0){
        //     layer.msg("工单完成不能为空", {icon: 2});
        //     return false;
        // }

        let cancelNodesArr = new Array();
        let cancelNode = $('input[name="workOrderCancelType"]');
        for (let k in cancelNode) {
            if (cancelNode[k].checked)
                cancelNodesArr.push(cancelNode[k].value);
        }
        if (cancelNodesArr.length == 0) {
            layer.msg("工单取消不能为空", {icon: 2});
            return false;
        }

        // data.workOrderCompleteType = completeNodesArr.join(",");
        data.workOrderCancelType = cancelNodesArr.join(",");

        // let specialOfferNodesArr = new Array();
        // let specialOfferNode = $('input[name="workOrderSpecialOfferType"]');
        // for(let k in specialOfferNode){
        //     if(specialOfferNode[k].checked)
        //         specialOfferNodesArr.push(specialOfferNode[k].value);
        // }
        // if (specialOfferNodesArr.length != 0) {
        //     data.workOrderSpecialOfferType = specialOfferNodesArr.join(",");
        // }


        let arr = new Array();
        $("input:checkbox[name='receivablesLimit']:checked").each(function (i) {
            arr[i] = $(this).val();
        });
        data.receivablesLimit = arr.join(",");//将数组合并成字符串

        // 渠道收尾款方
        let payerArr = new Array();
        $("input:checkbox[name='payer']:checked").each(function (i) {
            payerArr[i] = $(this).val();
        });
        data.payer = payerArr.join(",");//将数组合并成字符串

        let str = "<p><br/></p>";
        if (data.inviteCommentExplain && data.inviteCommentExplain.endsWith(str)) {
            data.inviteCommentExplain = data.inviteCommentExplain.substring(0, data.inviteCommentExplain.length - str.length);
        }

        if (data.payExplain && data.payExplain.endsWith(str)) {
            data.payExplain = data.payExplain.substring(0, data.payExplain.length - str.length);
        }
        let url = "/conf/channel/modifyOrderConfig.action";
        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json", dataType: "json", data: JSON.stringify(data),
            success: function (resp) {
                var message = resp.status == 200 ? "操作成功！" : resp.message;
                layer.msg(message);
                if (resp.status == 200) {
                    // zmnPage.direct("/channel/orderConfig.action?channelId=" + resp.id + "&addFlag=" + json.addFlag, 0);
                    zmnPage.reload(resp.message, 1000);
                }
            },
            error: function (XMLHttpRequest, status, errorThrown) {
            }
        });
        return false;
    });

    // $("input:checkbox:checked").each((i,e)=>{showPlatArr.push($(e).val())});

    // 允许工单特殊优惠：均不允许选项与运行后台，工程师APP，服务商门户三个互斥
    form.on('checkbox(workOrderSpecialOfferType)', function (obj) {
        let value = $(this).attr('value');
        let selectedFlag = $(this).prop('checked');
        if ((value == 1 || value == 2 || value == 3) && selectedFlag) {
            $("input:checkbox[name='workOrderSpecialOfferType'][value=5]").prop("checked", false);
            form.render(null);
        } else if (value == 5 && selectedFlag) {
            $("input:checkbox[name='workOrderSpecialOfferType'][value=1]").prop("checked", false);
            $("input:checkbox[name='workOrderSpecialOfferType'][value=2]").prop("checked", false);
            $("input:checkbox[name='workOrderSpecialOfferType'][value=3]").prop("checked", false);
            form.render(null);
        }
    });

    // 应用渠道
    zmnSelect.searchChannel('channelId', {
        selectedValues: json.channel.channelId === null ? null : json.channel.channelId,
        isRadio: true,
        remote: {
            events: {
                extendParams: function () {
                    return {
                        "rank": 2, //渠道层级：Integer类型；1-查询一级渠道，2-查询二级渠道,null不限
                    }
                }
            }
        },
        events: {
            changed: function (values) {
            }
        }
    });

    // C端收款限制
    form.on('radio(outReceivablesLimit)', function (obj) {
        if (obj.value == 3) {
            $('#payerDiv').show();
        } else {
            $('#payerDiv').hide();
        }
    });
    // 转换渠道
    form.on('radio(transType)', function (obj) {
        if (obj.value == 2) {
            $('#transDiv').show();
        } else {
            $('#transDiv').hide();
        }
    });
    // 核销码入口
    form.on('radio(codeEntry)', function (obj) {
        if (obj.value == 2) {
            $('#correctDiv').show();
        } else {
            $('#correctDiv').hide();
        }
    });

    // 转换渠道id
    let transChannel = xmSelect.render({
        el: '#transChannel',
        name: 'transChannel',
        radio: true,
        clickClose: true,
        filterable: true,
        initValue: [zmnUtil.isEmptyNull(json.orderConfig.transChannel) ? '' : json.orderConfig.transChannel],
        prop: {
            name: 'text',
        },
        data: json.channelList
    });

    form.on('radio(auditType)', function (obj) {
        // 不需审核隐藏 审核金额和部门
        if (obj.value == 1) {
            $("#auditMinPriceDiv").hide();
            $("#deptDiv").hide();
        } else {
            $("#auditMinPriceDiv").show();
            $("#deptDiv").show();
        }
    });

    form.on('radio(inviteComment)', function (obj) {
        if (obj.value == 1) {
            $("#inviteCommentPlatDiv").hide();
            $("#inviteCommentExplainDiv").hide();
        } else {
            $("#inviteCommentPlatDiv").show();
            $("#inviteCommentExplainDiv").show();
        }
    });

    form.on('radio(guideThirdPartPay)', function (obj) {
        if (obj.value == 1) {
            $("#payPlatDiv").hide();
            $("#payExplainDiv").hide();
            $("#qrPayDiv").hide();
        } else {
            $("#payPlatDiv").show();
            $("#payExplainDiv").show();
            $("#qrPayDiv").show();
        }
    });

    /**
     * 预付款按钮
     */
    form.on('radio(prepayType)', function (obj) {
        if (obj.value == 1) {
            $("#prepayDetail").hide();
            $("#prepayAmountDetail").val("");
        } else {
            $("#prepayDetail").show();
        }
    });

    //select 树
    zmnSelect.select({
        'deptSelect': {
            isRadio: true,
            selectedValues: [json.priceAuditDeptId], //已选中值（用于回显)
            clickClose: true,
            tree: {
                enable: true,
                //懒加载开关
                lazy: true,
                show: true,
                expandedKeys: json.expandedKeys,
                strict: false,
                events: {
                    load: function (item, callback) {
                        console.log(item.name + ":" + item.value);
                        // ajax请求
                        $.ajax({
                            method: 'post',
                            url: '/conf/channel/listChilds?parentId=' + item.value, //服务url
                        }).done(function (result) {
                            let res = result.data;
                            if (result.status == 200) {
                                if (zmnUtil.isObject(res) && res.status == 200) {
                                    callback(res.data);
                                } else if (zmnUtil.isArray(res)) {
                                    callback(res);
                                }
                            }
                        });
                    }
                }
            },
            propMap: {  //选项参数映射配置
                name: "name",   //显示值
                value: "value"  //选中值
            },
            remote: { //远程获取下拉数据
                enable: true, //开关：true-开启；false-关闭
                url: '/conf/channel/listChilds?selectVal=' + json.priceAuditDeptId, //服务url
            },
            events: {  //事件配置
                /**
                 * 选择中事件
                 * @param values 已选中值，Array类型
                 */
                changing: function (values) {
                    priceAuditDeptId = values[0];
                    // console.log("changing:" + values);
                },
                /**
                 * 选择完成后事件
                 * @param values 已选中值，Array类型
                 */
                changed: function (values) {
                    console.log("changed:" + values);
                }
            },
        }
    });

    // 系统后台录单 默认选中判断
    let accessModeStr = json.channel.accessMode;
    if (!zmnUtil.isEmptyNull(accessModeStr)) {
        if (!zmnUtil.isEmptyNull(json.orderConfig.hidden)) {
            return
        }
        // 判断 接入方式  1 话务接入, 2 H5, 3 API, 4 临时接入, 5 网络客服接入
        // 话务接入、网络客服接入
        if (accessModeStr.indexOf('1') > -1 || accessModeStr.indexOf('5') > -1) {
            //
            $("input[name='hidden'][value='2']").prop("checked", true);
        } else {
            $("input[name='hidden'][value='1']").prop("checked", true);
        }
        form.render('radio');
    }


    //对外暴露的接口
    exports('oms_conf_order_channel_detail');
    form.render();
});

function verifySubmitData(data) {
    if (zmnUtil.isEmptyNull(data.channelId)) {
        layer.msg("请选择渠道", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.hideOrderPrice)) {
        layer.msg("隐藏订单金额", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.outReceivablesLimit)) {
        layer.msg("C端收款限制必填", {icon: 2});
        return false;
    }

    if (data.outReceivablesLimit == 3 && zmnUtil.isEmptyNull(data.payer)) {
        layer.msg("收尾款方必填", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.inReceivablesLimit)) {
        layer.msg("F端收款限制必填", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.prepayType)) {
        layer.msg("改预付款必填", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.chargeDepositAmount)) {
        layer.msg("收取定金必填", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.checkSp)) {
        layer.msg("下单校验服务商必填", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.applique)) {
        layer.msg("贴花必填", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.autoCollectOrder)) {
        layer.msg("自动收单必填", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.autoDistributeOrder)) {
        layer.msg("自动派单必填", {icon: 2});
        return false;
    }

    // if (zmnUtil.isEmptyNull(data.applique)) {
    //     layer.msg("贴花必填", {icon: 2});
    //     return false;
    // }

    if (zmnUtil.isEmptyNull(data.showOrderPrice)) {
        layer.msg("透传订单价格必填", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.hidden)) {
        layer.msg("系统后台录单必填", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.portalAddOrder)) {
        layer.msg("渠道门户录单必填", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.sendMsg)) {
        layer.msg("发送短信必填", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.platformType)) {
        layer.msg("修改渠道必填", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.transType)) {
        layer.msg("转换渠道必填", {icon: 2});
        return false;
    }
    if (data.transType == 2 && zmnUtil.isEmptyNull(data.transTime)) {
        layer.msg("转换渠道时间必填", {icon: 2});
        return false;
    }
    // if (data.transType == 2 && zmnUtil.isEmptyNull(data.transChannel)) {
    //     layer.msg("联系电话所在渠道必填", {icon: 2});
    //     return false;
    // }

    if (zmnUtil.isEmptyNull(data.codeEntry)) {
        layer.msg("核销码入口必填", {icon: 2});
        return false;
    }

    if (data.codeEntry == 2 && zmnUtil.isEmptyNull(data.checkCorrect)) {
        layer.msg("校验准确性必填", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.orderTransferType)) {
        layer.msg("订单转单必填", {icon: 2});
        return false;
    }

    // if (zmnUtil.isEmptyNull(data.orderTransferType)) {
    //     layer.msg("订单转单必填", {icon: 2});
    //     return false;
    // }

    if (zmnUtil.isEmptyNull(data.auditType)) {
        layer.msg("服务审核必填", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.channelPortalDisplayOrder)) {
        layer.msg("渠道门户显示订单必填", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.inviteComment)) {
        layer.msg("邀评必填", {icon: 2});
        return false;
    }

    if (zmnUtil.isEmptyNull(data.guideThirdPartPay)) {
        layer.msg("引导去第三方平台支付必填", {icon: 2});
        return false;
    }
    return true;
}